package com.yunfeng.common.log.impl;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.google.common.collect.Maps;
import com.yunfeng.common.entity.impl.LogEntity;
import com.yunfeng.common.log.LogLevel;
import com.yunfeng.common.service.LogEntityService;
import com.yunfeng.common.shiro.ShiroDbRealm;

public class Log4JDBCImpl extends LogAdapter {

	private LogLevel rootLogLevel = LogLevel.ERROR;

	private LogEntityService logEntityService;

	private Map<String, LogLevel> customLogLevel = Maps.newHashMap();

	/**
	 * 
	 * @param message
	 * @param objects
	 * @param logLevel
	 * @see com.yunfeng.common.log.impl.LogAdapter#log(java.lang.String,
	 *      java.lang.Object[], com.yunfeng.common.log.LogLevel)
	 */
	@Override
	public void log(String message, Object[] objects, LogLevel logLevel) {

		MessageFormat mFormat = new MessageFormat(message);
		String result = mFormat.format(objects);

		if (!StringUtils.isNotBlank(result)) {
			return;
		}

		Subject subject = SecurityUtils.getSubject();
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject
				.getPrincipal();

		// result = shiroUser.toString() + ":" + result;

		LogEntity logEntity = new LogEntity();
		logEntity.setCreateTime(new Date());

		logEntity.setUsername(shiroUser.getLoginName());
		logEntity.setMessage(result);
		logEntity.setIpAddress(shiroUser.getIpAddress());
		logEntity.setLogLevel(logLevel);

		logEntityService.save(logEntity);
	}

	public void setRootLogLevel(LogLevel rootLogLevel) {
		this.rootLogLevel = rootLogLevel;
	}

	/**
	 * 
	 * @return
	 */
	@Override
	public LogLevel getRootLogLevel() {
		return rootLogLevel;
	}

	public void setCustomLogLevel(Map<String, LogLevel> customLogLevel) {
		this.customLogLevel = customLogLevel;
	}

	@Override
	public Map<String, LogLevel> getCustomLogLevel() {
		return customLogLevel;
	}

	public void setLogEntityService(LogEntityService logEntityService) {
		this.logEntityService = logEntityService;
	}

}
